
; define(function () {
	var defaultOptions = {
		"tplUrl": "/static/widgets/cafejs/script/warningLegend/warningLegend.html",
		"jsonUrl": "/static/widgets/cafejs/script/warningLegend/warningLegend.json",
		"imgUrl": "/static/widgets/cafejs/themes/default/warningLegend/img/",
		"container": "cafe-busis-container",					//容器  标签  id/class
		"bottom": 150,
		"z-index": 9999,
		"mapId": null,
		"callback": null										//回调函数(关闭窗口回调)

	};

	CafeJS.Legend = function (options) {
		var LegendObj = {
			_init: function () {
				$.extend(defaultOptions, options);
				if (!(defaultOptions.container.includes(".") && defaultOptions.container.indexOf(".") == 0) && !(defaultOptions.container.includes("#") && defaultOptions.container.indexOf("#") == 0)) {
					if ($("#" + defaultOptions.container).length > 0) {
						defaultOptions.container = "#" + defaultOptions.container;

					} else {
						defaultOptions.container = "." + defaultOptions.container;
					}
				}
				var $wrap = this.getTpl();
				var legendObj = this.getJson();
				this.initLayer($wrap, legendObj);
				this.bindEvent();
			},
			getTpl: function () {						//获取图例模板
				var html;
				$.ajax({
					type: "GET",
					url: defaultOptions.tplUrl,
					dataType: "html",
					async: false,
					success: function (res) {
						html = res;
					}
				});
				return $(html);
			},
			getJson: function (url) {				   //获取图例配置json数据
				var legendObj;
				$.ajax({
					type: "GET",
					url: defaultOptions.jsonUrl,
					dataType: "json",
					async: false,
					success: function (res) {
						legendObj = res;
					},
					error: function () {
						console.log(arguments);
					}
				});
				return legendObj;
			},
			initLayer: function ($wrap, legendObj) {		//初始化图例布局
				$(".warning-legend-wrap").remove();
				if (defaultOptions.right)
					$wrap.css({ "right": defaultOptions.right});
				else if (defaultOptions.left)
					$wrap.css({ "left": defaultOptions.left});
				else
					$wrap.css({ "left": 10});
				$(defaultOptions.container).append($wrap.css({"bottom": defaultOptions.bottom, "z-index": defaultOptions["z-index"] }));
				var $warp = $(".warning-legend-content-wrap");
				var $item = $wrap.find(".warning-legend-item").clone();
				var $title = $wrap.find(".warning-legend-title").clone();
				var $content = $wrap.find(".warning-legend-content").clone();
				$wrap.find(".warning-legend-item").remove();
				$(legendObj.legends).each(function (a, legend) {
					var $itemT = $item.clone();
					$itemT.find(".warning-legend-title").remove();
					$itemT.find(".warning-legend-content").remove();
					var $titleT = $title.clone();
					$titleT.text(legend.title);
					$itemT.append($titleT);
					$(legend.products).each(function (b, pro) {
						var $contentT = $content.clone();
						$contentT.find(".warning-legend-content-product-type input").attr("id", "legend-" + pro.id);
						$contentT.find(".warning-legend-content-product-type label").text(pro.name).attr("item", pro.id).attr("for", "legend-" + pro.id).attr("hasLevel", pro.flag);
						if (!pro.name) {
							$contentT.find(".warning-legend-content-product-type").hide();
							$contentT.find(".warning-legend-content-product-level").css('margin-top', '10px');
						}
						
						var trNum = 1;
						$(pro.levels).each(function (c, level) {
							var $eachDiv;
							if (pro.flag) {
								$eachDiv = $("<div class='eachProLevel' item='true'><div item='name'></div><div item='icon'></div><div item='mark'></div><div item='val'></div><span item='unit'></span></div>");
								if (level.level != '5')
									$eachDiv.addClass('pro-selected')
								$eachDiv.addClass(level["class"]).attr("key", level.key).attr("level", level.level);
								$eachDiv.attr("update", level["update"]);
								if (pro.id != level.key) {
									$eachDiv.find("div[item='name']").text(level.name);
									if (!level.name) {
										$eachDiv.find("div[item='name']").hide();
									}
									if (pro.id == 'S_STRONG') {
										$eachDiv.find("div[item='icon']").append($("<img width=100% height=100% src='" + defaultOptions.imgUrl + level.icon + "'/>"));
									} else {
										$eachDiv.find("div[item='icon']").append($("<img width=100% height=100% src='" + defaultOptions.imgUrl + level.icon + "'/>"));
									}
									$eachDiv.find("div[item='mark']").text(level.mark);
									$eachDiv.find("div[item='val']").text(level.val);
									$eachDiv.find("span[item='unit']").text(level.unit);
								} else {
									$eachDiv.find("div[item='icon']").append($("<img width=100% height=100% src='" + defaultOptions.imgUrl + level.icon + "'/>"));
									$eachDiv.find("div[item='mark']").text(level.mark);
									$eachDiv.find("div[item='val']").text(level.val);
									$eachDiv.find("span[item='unit']").text(level.unit);
								}
								$contentT.find(".warning-legend-content-product-level").append($eachDiv);
							} else {
								trNum = Math.ceil((c + 1) / 3);
								$eachDiv = $("<div class='eachProLevel' item='false'><div item='icon'></div><div item='name'></div></div>");
								if (level.level != '5')
									$eachDiv.addClass('pro-selected')
								$eachDiv.addClass(level["class"]).attr("key", level.key).attr("level", level.level);
								$eachDiv.attr("update", level["update"]);
								$eachDiv.find("div[item='icon']").append($("<img width=100% height=100% src='" + defaultOptions.imgUrl + level.icon + "'/>"));
								$eachDiv.find("div[item='name']").text(level.name);
								$contentT.find(".warning-legend-content-product-level").append($eachDiv);
							}
						})
						//$contentT.find(".warning-legend-content-product-level").css({"height":30*trNum + 5 + "px"});			//30 - css 中  eachProLevel 的高度
						if (pro.width)
							$contentT.css('width', pro.width);
						$itemT.append($contentT);
					})
					$warp.append($itemT);
				})
			},
			openWin: function () {								//打开弹窗
				$(".warning-legend-wrap").show();
			},
			closeWin: function () {								//关闭弹窗
				$(".warning-legend-wrap").hide();
				if ($.isFunction(defaultOptions.callback)) {
					defaultOptions.callback();
				}
			},
			removeWin: function() {								//移除弹窗
				$(".warning-legend-wrap").remove();
				if ($.isFunction(defaultOptions.callback)) {
					defaultOptions.callback();
				}
			},
			fillVal: function (info) {							//填充值
				$(".warning-legend-wrap").find(".eachProLevel[update=true]").each(function () {
					var eachKey = $(this).attr("key");
					var val = info[eachKey];
					$(this).find("div[item='val']").text(val);
				})
			},
			isActive: function(id) { // 是否选中
				var isActive = true;
				if ($(defaultOptions.container).find('div[key='+id+']').length > 0)
					isActive = $(defaultOptions.container).find('div[key='+id+']').hasClass('pro-selected');
				return isActive;
			},
			//searchData -- 单个     visible--true/false
			showOrHideLayer: function (searchData, visible) {		//显示隐藏图层
				var layerId = GLMap.layerIds;
				for (var i = 0; i < layerId.length; i++) {
					if (layerId[i].includes(searchData)) {
						GIS.LayerControll.showControll(defaultOptions.mapId, layerId[i], visible);
					}
				}
			},
			bindEvent: function () {
				var that = this;
				//单击弹出框的头部，确定点击处的位置
				$(".warning-legend-title-wrap").mousedown(function (event) {
					$(this).css({ "cursor": "all-scroll" });			    //点击鼠标切换为手势图形
					event.stopPropagation();
					event.preventDefault();
					var isMove = true;
					var _this = $(".warning-legend-wrap");
					var m_x = Number(_this.css("right").split("px")[0]);	//点击窗体时，right
					var m_y = Number(_this.css("bottom").split("px")[0]);	//点击窗体时，bottom
					var abs_x = event.pageX;		//点击窗体时，左边距
					var abs_y = event.pageY;		//点击窗体时，上边距
					//单击住头部可进行拖拽，计算移动大小，以及移动范围限制
					$(document).unbind('mousemove').bind('mousemove', function (event) {
						if (isMove) {
							//event.pageX,移动后的左边距;event.pageY,移动后的上边距
							var ebs_x = m_x - (event.pageX - abs_x); 			//移动后的right
							var ebs_y = m_y - (event.pageY - abs_y);			//移动后的bottom
							var body_w = $(defaultOptions.container).width();
							var body_h = $(defaultOptions.container).height();
							var div_w = _this.width();
							var div_h = _this.height();
							//不可超出左右边框
							if (ebs_x <= 0) {
								ebs_x = 0;
							} else if (ebs_x > body_w - div_w) {
								ebs_x = body_w - div_w;
							}
							//不可超出上下边框
							if (ebs_y <= 0) {
								ebs_y = 0;
							} else if (ebs_y > body_h - div_h) {	//减去上下的蓝边高
								ebs_y = body_h - div_h;
							}
							//重新设定弹出框的左边距，上边距
							_this.css({ 'right': ebs_x, 'bottom': ebs_y });
						}
					}).mouseup(function () {
						isMove = false
						$(document).unbind('mousemove');
						//	$(".warning-legend-title-wrap").css({"cursor": "default"});//点击鼠标切换为手势图形
					});//鼠标移除事件；单击事件结束事件。
				});

				//关闭弹窗事件
				$(".warning-legend-title-wrap .warning-legend-title-close").off("click").on("click", function () {
					that.closeWin();
				});

				//全选事件
				$(".warning-legend-content-wrap .warning-legend-content-product-type input").off("change").on("change", function () {
					debugger;
					var checkedFlag = $(this).prop("checked");						//是否选中(即显示隐藏)
					var hasLevelFlag = $(this).next("label").attr("haslevel");		//是否有级别 
					var item = $(this).next("label").attr("item");
					$(this).parent().siblings(".warning-legend-content-product-level").find(".eachProLevel").each(function () {
						if (checkedFlag) {
							$(this).addClass("pro-selected");
						} else {
							$(this).removeClass("pro-selected");
						}

						var proId = $(this).attr("key");
						var searchData = proId;
						that.showOrHideLayer(searchData, checkedFlag);
					});
				});

				//单选事件
				$(".warning-legend-content-wrap .warning-legend-content-product-level .eachProLevel").off("click").on("click", function () {
					var visable;
					var item = $(this).attr("key");					//类型
					var level = $(this).attr("level");				//级别
					debugger
					var searchData;
					if ($(this).hasClass("pro-selected")) {
						visable = false;
						$(this).removeClass("pro-selected");
					} else {
						visable = true;
						$(this).addClass("pro-selected");
					}

					searchData = item;
					that.showOrHideLayer(searchData, visable);
				});
			}
		}
		LegendObj._init();
		return LegendObj;
	}

});
